package com.chencq.core.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha1Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chencq.module.user.entity.User;

@Controller
@RequestMapping("/*")
public class CommonController {

	@RequestMapping("/login.html")
	public String goLogin(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		return "login";
	}
  
	/**
	 * 登录
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String userName=request.getParameter("userName");
		String passWord=request.getParameter("passWord");
		UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
		Subject currentUser = SecurityUtils.getSubject();
		String errorMessage = "";
		try {
			currentUser.login(token);
			//获取所有用户信息，权限由前端shiro标签控制
			return "redirect:index.html";
		} catch (UnknownAccountException e) {
			errorMessage = "用户不存在";
		} catch (IncorrectCredentialsException e) {
			errorMessage = "密码错误";
		} catch (LockedAccountException e) {
			errorMessage = "用户锁定";
		} catch (DisabledAccountException e) {
			errorMessage = "用户被禁止";
		} catch (AuthenticationException e) {
			errorMessage = "未知错误";
		}
		model.addAttribute("errorMessage", errorMessage);
		return "login";
	}
	
	@RequestMapping("/index.html")
	public String goIndex(HttpServletRequest req, HttpServletResponse res, ModelMap model) {
		Subject currentUser = SecurityUtils.getSubject();
		User user = (User)currentUser.getPrincipal();
		model.put("user", user);
		return "index";
	}
	
	/**
	 * 注销
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest req, HttpServletResponse res, ModelMap model){
		SecurityUtils.getSubject().logout();
		return "redirect:loginUI";
	}
	
	@RequestMapping("/error404.html")
	public String error404(HttpServletRequest req, HttpServletResponse res, ModelMap model){
		return "error404";
	}
	@RequestMapping("/error500.html")
	public String error500(HttpServletRequest req, HttpServletResponse res, ModelMap model){ 
		return "error500";
	}
	@RequestMapping("/error403.html")
	public String error401(HttpServletRequest req, HttpServletResponse res, ModelMap model){
		return "error403";
	}
	
}
